//
//  SubmitOrderViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/5/10.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "SubmitOrderViewController.h"
#import "AddressTableViewCell.h"
#import "CollectTreaTableViewCell.h"
#import "OrderTableViewCell.h"
#import "OrderModel.h"
#import "ZJDeliveryAddressViewController.h"
#import "PayViewController.h"
#import "ShopDetailViewController.h"
@interface SubmitOrderViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UITextField * debitTf;
@property (nonatomic, strong) UITextField * remarkTf;
@property (nonatomic, strong) NSArray  *shopArray;
@property (nonatomic, strong) MYLabel  *payLabel;
@property (nonatomic, strong) OrderModel  *shopModel;
@property (nonatomic, strong) NSString    *addressId;
//因为数据是传过来的，假如用户刚注册传过来的数组是没有地址的，当选择地址之后传过来的只是赋值给了UI，但是数据里的地址依然为空，刷新时候用的是数据。所以会出现选了地址之后滑动表，结果地址依然没有（实际是有的），所以创个字典存储选择的内容、如果数据跟创建的字典都没有数据时后。

@property (nonatomic, strong) NSMutableDictionary *newDic;//存储选择的地址信息


@end

@implementation SubmitOrderViewController
-(NSMutableDictionary *)newDic{
    if (!_newDic) {
        _newDic=[NSMutableDictionary dictionary];
    }
    return _newDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"提交订单";
   
    [self.view addSubview:self.tableView];
    //添加手势 处理键盘
    [self fingerView];
   //创建其他视图
    [self establishOtherView];
   
    self.newDic=self.orderDic[@"address"];
    // Do any additional setup after loading the view.
}
-(void)establishOtherView{
    UIView*bottomView=[[UIView alloc]initWithFrame:CGRectMake(0,MainH-50-64, MainW, 50)];
    bottomView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bottomView];
    UILabel*label=[[UILabel alloc]init];
    label.text=[NSString stringWithFormat:@"%@",MyString(@"实际付款:")];
    label.textColor=TextColor3;
    label.font=FontAndStyle12;
    CGSize size=[label.text sizeWithAttributes:@{NSFontAttributeName:label.font }];
    label.frame=CGRectMake(10, 0, size.width, 50);
    self.payLabel=[[MYLabel alloc]initWithFrame:CGRectMake(label.bsg_right+3, 0, 0.65*MainW-20-size.width, 50)];
    self.payLabel.text=[NSString stringWithFormat:@"¥ %@",self.orderDic[@"payment"]];
    self.payLabel.font=FontAndStyle14;
    self.payLabel.textColor=Red_Color;
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0.65*MainW, 0, 0.35*MainW, 50)];
    btn.backgroundColor=Red_Color;
    [btn setTitle:MyString(@"提交订单") forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn addTarget:self action:@selector(submitOrderClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn];
    [bottomView addSubview:label];
    [bottomView addSubview:self.payLabel];
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-64-50) style:UITableViewStyleGrouped];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.separatorColor=SeparatorColor;
        _tableView.separatorInset=UIEdgeInsetsZero;
        [_tableView registerNib:[UINib nibWithNibName:@"AddressTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"AddressTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"OrderTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"OrderTableViewCell"];
    }
    return _tableView;
}
#pragma  mark -----提交订单-----
-(void)submitOrderClick{
    if ([self.addressId intValue]==-100) {
        [self showToast:MyString(@"请填写收货地址!")];
        return;
    }
    if (self.styple==NearBuy||self.styple==Description) {
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        if (self.nearDic!=nil) {
            dic=self.nearDic;
        }
        
        dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
        dic[@"skuId"]=self.shopModel.skuId;
        dic[@"addressId"]=self.addressId;
        dic[@"number"]=self.shopModel.quantity;
        dic[@"remark"]=self.debitTf.text;
        if (self.remarkTf.text.length!=0) {
            dic[@"invoice"]=@"1";
        }else{
            dic[@"invoice"]=@"0";
        }
        NSLog(@"----%@",dic);
        [self doHttpRequestWithApi:API_SubmitOrderNow method:POST dic:dic successBlock:^(NSDictionary *dic) {
            NSLog(@"提交订单 %@",dic);
            PayViewController *vc=[[PayViewController alloc]init];
            vc.orderSn=[NSString stringWithFormat:@"%@",dic[@"data"][@"payNo"]];
            vc.orderDic=[dic[@"data"] copy];
            if (self.styple==NearBuy) {
                vc.isNear=YES;
            }else{
                vc.isNear=NO;
            }
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }];
    }else if (self.styple==Supplication){
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
        dic[@"skuId"]=self.shopModel.skuId;
        dic[@"addressId"]=self.addressId;
        dic[@"number"]=self.shopModel.quantity;
        dic[@"remark"]=self.debitTf.text;
        if (self.remarkTf.text.length!=0) {
            dic[@"invoice"]=@"1";
        }else{
            dic[@"invoice"]=@"0";
        }
        
        [self doHttpRequestWithApi:API_SubmitOrderNow method:POST dic:dic successBlock:^(NSDictionary *dic) {
            NSLog(@"提交订单 %@",dic);
            NSArray*array=dic[@"data"][@"trxNos"];
            [self prayRequestLoad:array[0]];
            PayViewController *vc=[[PayViewController alloc]init];
            vc.orderSn=[NSString stringWithFormat:@"%@",dic[@"data"][@"payNo"]];
            vc.orderDic=[dic[@"data"] copy];
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }];
    }else{
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
        dic[@"skuIds"]=[self.skuIdsArray mj_JSONString];
        dic[@"addressId"]=self.addressId;
        dic[@"remark"]=self.debitTf.text;
        if (self.remarkTf.text.length!=0) {
            dic[@"invoice"]=@"1";
        }else{
            dic[@"invoice"]=@"0";
        }
        [self doHttpRequestWithApi:API_SubmitOrder method:POST dic:dic successBlock:^(NSDictionary *dic) {
            NSLog(@"提交订单 %@",dic);
            PayViewController *vc=[[PayViewController alloc]init];
            vc.orderSn=[NSString stringWithFormat:@"%@",dic[@"data"][@"payNo"]];
            vc.orderDic=[dic[@"data"] copy];
            [self.navigationController pushViewController:vc animated:YES];
            
        }];
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else if (section==1){
        self.shopArray=[OrderModel mj_objectArrayWithKeyValuesArray:self.orderDic[@"skus"]];
        return self.shopArray.count;
    }else{
        return 2;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        AddressTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"AddressTableViewCell"];
        if ([self.orderDic[@"address"] isEqual:[NSNull null]]&&[self.newDic isEqual:[NSNull null]]) {
            cell.nameLabel.hidden=YES;
            cell.phonelabel.hidden=YES;
            cell.addressLabel.hidden=YES;
            cell.addAddress.hidden=NO;
            self.addressId=@"-100";
        }else{
            NSDictionary*dic;
            if ([self.orderDic[@"address"] isEqual:[NSNull null]]) {
                dic=self.newDic;
            }else{
                dic=self.orderDic[@"address"];
            }
            
            cell.nameLabel.hidden=NO;
            cell.phonelabel.hidden=NO;
            cell.addressLabel.hidden=NO;
            cell.addAddress.hidden=YES;
            cell.nameLabel.text=[NSString stringWithFormat:@"收货人:%@",dic[@"consigneeName"]];
            cell.phonelabel.text=[NSString stringWithFormat:@"%@",dic[@"consigneePhone"]];
            NSString *str=[NSString stringWithFormat:@"%@%@",dic[@"area"],dic[@"detail"]];
            if ([dic[@"isDefault"] intValue]==1) {//默认
                NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",@"[默认地址]",str]];
                [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,6)];
                cell.addressLabel.attributedText=str2;
            }else{
                cell.addressLabel.text=[NSString stringWithFormat:@"收货地址:%@",str];
            }
            self.addressId=dic[@"addressId"];
            
        }
        return cell;
    }else if (indexPath.section==1){
        self.shopModel=self.shopArray[indexPath.row];
        OrderTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"OrderTableViewCell"];
        [cell.shopImg sd_setImageWithURL:[NSURL URLWithString:self.shopModel.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
        cell.tagArray=self.shopModel.serves;
        [cell creatOrderCellView];
        
        
        
        cell.shopName.text=self.shopModel.spuName;
        cell.shopDetail.text=self.shopModel.saleName;
        cell.shopPrice.text=[NSString stringWithFormat:@"¥ %@",self.shopModel.price];
        cell.shopNumber.text=[NSString stringWithFormat:@"× %@",self.shopModel.quantity];
        
        return cell;
    }else{
        NSString * hjID = [NSString stringWithFormat:@"%ldcell%ld",indexPath.section,indexPath.row];
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:hjID];
        if (!cell) {
             cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:hjID];
        }
        cell.selectionStyle=0;
        cell.textLabel.textColor=TextColor6;
        cell.detailTextLabel.textColor=TextColor6;
        cell.textLabel.font=FontAndStyle14;
        cell.detailTextLabel.font=FontAndStyle12;
        if (indexPath.row==0) {
            if (self.debitTf==nil) {
                self.debitTf=[[UITextField alloc]initWithFrame:CGRectMake(60, 10, MainW-80, 30)];
                [self.debitTf setFont:FontAndStyle12];
                self.debitTf.textColor=TextColor6;
                self.debitTf.delegate=self;
                self.debitTf.placeholder=MyString(@"说明啊");
                [self.debitTf setValue:TextColor9 forKeyPath:@"_placeholderLabel.textColor"];
                [self.debitTf setValue:FontAndStyle12 forKeyPath:@"_placeholderLabel.font"];
                self.debitTf.borderStyle=0;
            }
            [cell addSubview:self.debitTf];
            //self.debitTf.bsg_centerY=cell.bsg_centerY;
            cell.textLabel.text=MyString(@"备注");
        }else if(indexPath.row==2){
            if (self.remarkTf==nil) {
                self.remarkTf=[[UITextField alloc]initWithFrame:CGRectMake(60, 10, MainW-80, 30)];
                [self.remarkTf setFont:FontAndStyle12];
                self.remarkTf.textColor=TextColor6;
                self.remarkTf.delegate=self;
                self.remarkTf.placeholder=MyString(@"发票啊");
                [self.remarkTf setValue:TextColor9 forKeyPath:@"_placeholderLabel.textColor"];
                [self.remarkTf setValue:FontAndStyle12 forKeyPath:@"_placeholderLabel.font"];
                self.remarkTf.borderStyle=0;
            }
            [cell addSubview:self.remarkTf];
            //self.debitTf.bsg_centerY=cell.bsg_centerY;
            cell.textLabel.text=MyString(@"发票:");
        }else{
            cell.selectionStyle=0;
            cell.textLabel.text=MyString(@"配型方式");
            cell.detailTextLabel.text=MyString(@"快递");
        }

        return cell;
    }
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        AddressTableViewCell*cell=[tableView cellForRowAtIndexPath:indexPath];
        ZJDeliveryAddressViewController*vc=[[ZJDeliveryAddressViewController alloc]init];
        vc.styple=1;
        vc.addressBlock=^(ZJAdressModel *model){
            cell.nameLabel.hidden=NO;
            cell.phonelabel.hidden=NO;
            cell.addressLabel.hidden=NO;
            cell.addAddress.hidden=YES;
            cell.nameLabel.text=[NSString stringWithFormat:@"收货人:%@",model.consigneeName];
            cell.phonelabel.text=[NSString stringWithFormat:@"%@",model.consigneePhone];
            self.addressId=model.addressId;
            NSString* str=[NSString stringWithFormat:@"%@%@",[model.area stringByReplacingOccurrencesOfString:@" " withString:@""],model.detail];
            if (model.isDefault==1) {//默认
                NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",@"[默认地址]",str]];
                [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,6)];
                cell.addressLabel.attributedText=str2;
            }else{
                cell.addressLabel.text=[NSString stringWithFormat:@"收货地址:%@",str];
            }
            self.newDic=[NSMutableDictionary dictionary];
            [self.newDic setObject:model.addressId forKey:@"addressId"];
            [self.newDic setObject:model.area forKey:@"area"];
            [self.newDic setObject:model.consigneeName forKey:@"consigneeName"];
            [self.newDic setObject:model.detail forKey:@"detail"];
            [self.newDic setObject:model.consigneePhone forKey:@"consigneePhone"];
            [self.newDic setObject:[NSString stringWithFormat:@"%ld",(long)model.isDefault] forKey:@"isDefault"];
            [self.newDic setObject:model.userId forKey:@"userId"];
            //[self.tableView reloadData];

        };
        [self.navigationController pushViewController:vc  animated:YES];
    }else if(indexPath.section==1){
        self.shopModel=self.shopArray[indexPath.row];
        ShopDetailViewController*vc=[[ShopDetailViewController alloc]init];
        vc.spuId=self.shopModel.skuId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0||indexPath.section==1) {
        return 100;
    }else{
        return 49;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 5;
    }else if (section==1){
        return 100;
    }else{
        return 0.01;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==1) {
        UIView*view1=[[UIView alloc]init];
        view1.backgroundColor=Gray_Color;
        UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, MainW, 49)];
        view.backgroundColor=[UIColor whiteColor];
        [view1 addSubview:view];
        UILabel *label=[[UILabel alloc]init];
        label.textColor=Red_Color;
        label.text=[NSString stringWithFormat:@"¥ %@",self.orderDic[@"price"]];
        label.font=[UIFont systemFontOfSize:15];
        CGSize size=[label.text sizeWithAttributes:@{NSFontAttributeName:label.font }];
        label.frame=CGRectMake(MainW-size.width-10, 0, size.width, 49);
        [view addSubview:label];
        UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, MainW-20-size.width-3, 49)];
        lable.text=[NSString stringWithFormat:@"共计%@件商品  合计:",self.orderDic[@"quantity"]];
        lable.textAlignment=NSTextAlignmentRight;
        lable.textColor=TextColor6;
        lable.font=FontAndStyle12;
        [view addSubview:lable];
        return  view1;
    }else{
        return nil;
    }
}
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    NSLog(@"keyBoard:%f", keyboardSize.height);  //216
    ///keyboardWasShown = YES;
}
- (void) keyboardWasHidden:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    self.tableView.contentOffset=CGPointMake(0, 0);
    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
    // keyboardWasShown = NO;
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.tableView.contentOffset=CGPointMake(0, 316+self.shopArray.count*50);
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.tableView.contentOffset=CGPointMake(0, 0);
    [self.debitTf endEditing:YES];
    [self.remarkTf endEditing:YES];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[self.tableView class]]) {
        return YES;
    }
    
    return  NO;
}
-(void)fingerView{
    //self.tableView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    singleTap.delegate=self;
    [self.tableView addGestureRecognizer:singleTap];
}
//键盘收起
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
    
}
-(void)prayRequestLoad:(NSString*)orderSn{
    self.Praydic[@"orderSn"]=orderSn;
    if (self.Praydic[@"prayId"]==nil) {
        [self doHttpRequestWithApi:userprayadd method:GET dic:self.Praydic successBlock:^(NSDictionary *dic) {
            //[MBProgressHUD showSuccess:@"祈愿成功!"];
            
        }];
    }else{
        [self doHttpRequestWithApi:userpraychange method:GET dic:self.Praydic successBlock:^(NSDictionary *dic) {
            
        }];
    }
    
    
}
@end
